<?php

/**
 * This file is part of the Framework03 PHP framework.
 * @author Walter Tamboer
 * @package Framework03
 */

/**
 * This class is able to render Xsl views.
 */
class FW_View_Xsl extends FW_View_Abstract
{
	/**
	 * @var DOMDocument The XML DOM document.
	 */
	private $dom;

	/**
	 * @var string The xsl file used to process the XML.
	 */
	private $xslName;

    /**
     * @var string The extensions of the file to render.
     */
    private $extension = '.xsl';

    /**
     * Initializes a new instance of this class.
	 * @param DOMDocument $dom The DOMDocument to use.
	 * @param string $xslName The XSL file used to process XML.
     */
    public function __construct(DOMDocument $dom, $xslName = '')
    {
        if (!extension_loaded('xsl'))
            throw new FW_View_Exception("Xsl extension isn't loaded!", 500);
            
        $this->dom = $dom;
        $this->xslName = $xslName;
    }
    
    /**
     * Gets the path to the Xsl file used to process the xml.
     * @param FW_Controller_Action $controller The controller that wants the rendering to be done.
     * @param string $actionName The name of the action that wants the rendering to be done.
     * @return string Returns a string which represents the path to the xsl file.
     */
    private function getXslPath(FW_Controller_Action $controller, $actionName)
    {
        if (empty($this->xslName))
            $this->xslName = strtolower(substr($actionName, 0, -6));

        $dispatcher = $controller->getDispatcher();

        $directory = $dispatcher->getControllerDirectory();

        $path = dirname($directory)
            . DIRECTORY_SEPARATOR
            . 'views'
            . DIRECTORY_SEPARATOR
            . 'scripts'
            . DIRECTORY_SEPARATOR
            . strtolower(substr(get_class($controller), 0, -10))
            . DIRECTORY_SEPARATOR
            . $this->xslName
            . $this->extension;

        return $path;
    }

    /**
     * Renders the view to the screen.
     * @param FW_Controller_Action $controller The controller that wants the rendering to be done.
     * @param string $actionName The name of the action that wants the rendering to be done.
     */
    public function render(FW_Controller_Action $controller, $actionName)
    {
		// Create the XSL document
		$dom = new DOMDocument;
		$dom->load($this->getXslPath($controller, $actionName));

		// Create the XSL translator
		$xsl = new XSLTProcessor();
		$xsl->importStylesheet($dom);

		echo $xsl->transformToXml($this->dom);
    }
}
